package com.ttpai.boot.lbs.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class UrlUtil {

    private static final Logger logger = LoggerFactory.getLogger(UrlUtil.class);

    private static String UTF8 = "UTF-8";

    public static String decode(String decoded) {
        return decode(decoded, UTF8);
    }

    /**
     * 解码两次
     */
    public static String decode2(String decoded) {
        return decode(decode(decoded, UTF8), UTF8);
    }

    public static String decode(String decoded, String charset) {
        try {
            decoded = URLDecoder.decode(decoded, charset);
        } catch (UnsupportedEncodingException e) {
            logger.error("未知的编码方式", e);
        }
        return decoded;
    }

    public static String encode(String encoded) {
        return encode(encoded, UTF8);
    }

    /**
     * 编码两次
     */
    public static String encode2(String encoded) {
        return encode(encode(encoded, UTF8), UTF8);
    }

    public static String encode(String encoded, String charset) {
        try {
            encoded = URLEncoder.encode(encoded, charset);
        } catch (UnsupportedEncodingException e) {
            logger.error("未知的编码方式", e);
        }
        return encoded;
    }
}
